// 电话随访模块前端JS（全局唯一配置驱动版，支持查询、录入、历史、导出、日志恢复）

// ✅全局变量定义（移出DOMContentLoaded作用域）
let selectedStudent = null;
let currentRecords = [];
let editingRecordId = null;
let followupConfig = null;
let queryFieldsConfig = null;
let historyFieldsConfig = null;
let searchResultConfig = null;

// ✅新增：加载随访配置（严格配置驱动，无兜底方案）
async function loadFollowupConfig() {
  console.log("🔧 开始加载随访配置...");
  
  // 1. 获取查询字段配置（严格要求成功）
  try {
    const queryFieldsResp = await fetch("/api/config/query-fields");
    if (!queryFieldsResp.ok) {
      throw new Error(`查询字段配置API失败: ${queryFieldsResp.status}`);
    }
    const queryFieldsData = await queryFieldsResp.json();
    if (!queryFieldsData.success) {
      throw new Error(`查询字段配置返回失败: ${queryFieldsData.message}`);
    }
    queryFieldsConfig = queryFieldsData.fields;
    console.log("✅ 查询字段配置加载成功:", queryFieldsConfig);
    renderQueryArea();
  } catch (error) {
    console.error("❌ 查询字段配置加载失败:", error);
    throw new Error(`配置驱动架构要求查询字段配置必须成功: ${error.message}`);
  }    // 2. 获取历史记录字段配置（严格要求成功）
    try {
      const historyFieldsResp = await fetch("/api/config/history_fields/followup");
      if (!historyFieldsResp.ok) {
        throw new Error(`历史字段配置API失败: ${historyFieldsResp.status}`);
      }
      const historyFieldsData = await historyFieldsResp.json();
      if (!historyFieldsData.success) {
        throw new Error(`历史字段配置返回失败: ${historyFieldsData.message}`);
      }
      historyFieldsConfig = historyFieldsData.fields;
      console.log("✅ 历史记录字段配置加载成功:", historyFieldsConfig);
  } catch (error) {
    console.error("❌ 历史字段配置加载失败:", error);
    throw new Error(`配置驱动架构要求历史字段配置必须成功: ${error.message}`);
  }

  // 3. 获取查询结果表格配置（严格要求成功）
  try {
    const searchResultResp = await fetch("/api/config/search_result_fields/followup");
    if (!searchResultResp.ok) {
      throw new Error(`查询结果配置API失败: ${searchResultResp.status}`);
    }
    const searchResultData = await searchResultResp.json();
    if (!searchResultData.success) {
      throw new Error(`查询结果配置返回失败: ${searchResultData.message}`);
    }
    searchResultConfig = searchResultData;
    console.log("✅ 查询结果表格配置加载成功:", searchResultConfig);
  } catch (error) {
    console.error("❌ 查询结果配置加载失败:", error);
    throw new Error(`配置驱动架构要求查询结果配置必须成功: ${error.message}`);
  }
  
  // 4. 获取完整随访配置（严格要求成功）
  try {
    const response = await fetch("/api/followup_records/config");
    if (!response.ok) {
      throw new Error(`随访配置API失败: ${response.status}`);
    }
    const data = await response.json();
    if (!data.success) {
      throw new Error(`随访配置返回失败: ${data.message}`);
    }
    
    // 获取表单字段详细配置
    const formFieldsResp = await fetch("/api/config/followup_form_fields");
    const formFieldsData = await formFieldsResp.json();
    
    if (formFieldsData.success) {
      followupConfig = {
        form_fields: formFieldsData.fields,
        field_mapping: data.config.field_mapping || {},
        select_options: data.config.select_options || {},
        validation_rules: data.config.validation_rules || {}
      };
      
      console.log("✅ 随访配置加载成功:", followupConfig);
      
      // 初始化表单配置
      initializeFormWithConfig();
    } else {
      throw new Error(`表单字段配置返回失败: ${formFieldsData.message}`);
    }
  } catch (error) {
    console.error("❌ 随访配置加载失败:", error);
    throw new Error(`配置驱动架构要求随访配置必须成功: ${error.message}`);
  }
  
  console.log("✅ 所有配置加载完成，配置驱动架构初始化成功");
}

// ✅新增：使用FixedQueryArea渲染查询区
function renderQueryArea() {
  if (!queryFieldsConfig) {
    console.warn("⚠️ 查询配置未加载，跳过查询区渲染");
    return;
  }
  
  console.log("🔧 开始渲染配置驱动查询区:", queryFieldsConfig);
  
  if (window.renderFixedQueryArea) {
    window.renderFixedQueryArea(
      queryFieldsConfig,
      "fixedQueryArea",
      onSearch,
      onClear,
      false // 禁用列配置按钮
    );
  } else {
    console.error("❌ FixedQueryArea.js 未正确加载");
  }
}

// ✅新增：查询按钮回调（严格配置驱动）
function onSearch(params) {
  // 严格检查查询结果配置
  if (!searchResultConfig || !searchResultConfig.columns) {
    console.error("❌ 查询结果配置未加载，无法执行查询");
    if (window.Swal) {
      Swal.fire("配置错误", "查询结果配置未加载，请刷新页面重试", "error");
    }
    return;
  }
  
  // 添加分页参数
  const searchParams = new URLSearchParams(params);
  const page = params.page || '1';
  searchParams.set('page', page);
  searchParams.set('per_page', '10');
  
  // 使用配置API提供的列配置（严格配置驱动）
  searchParams.set('columns', searchResultConfig.columns.join(','));
  
  // 调用统一查询接口
  fetch(`/api/students/query?${searchParams.toString()}`)
    .then((response) => {
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }
      return response.json();
    })
    .then((data) => {
      console.log(`✅ 查询成功，共 ${data.total} 条记录，当前第 ${data.page} 页`);
      if (data.success) {
        // 严格配置驱动：API响应数据完整性验证
        if (data.students === undefined || data.total === undefined || data.page === undefined || data.per_page === undefined) {
          throw new Error("配置驱动架构错误：API响应数据不完整，必须包含 students, total, page, per_page 字段");
        }
        
        const students = data.students;
        const total = data.total;
        const pageNum = data.page;
        const perPage = data.per_page;
        
        renderStudentTableWithComponent(students);
        renderPagination(total, pageNum, perPage);
      } else {
        console.error("❌ 查询失败:", data.message || data.error);
        renderStudentTableWithComponent([]);
        if (window.Swal) {
          Swal.fire("查询失败", data.message || data.error || "未知错误", "error");
        }
      }
    })
    .catch((error) => {
      console.error("❌ 查询异常:", error);
      renderStudentTableWithComponent([]);
      if (window.Swal) {
        Swal.fire("查询失败", `网络或服务器错误: ${error.message}`, "error");
      }
    });
}

// ✅新增：清除按钮回调
function onClear() {
  renderStudentTableWithComponent([]);
  renderPagination(0, 1, 10);
}

// ✅新增：获取当前查询参数
function getCurrentQueryParams() {
  const params = {};
  const queryInputs = document.querySelectorAll('#fixedQueryArea input, #fixedQueryArea select');
  queryInputs.forEach(input => {
    if (input.value && input.name) {
      params[input.name] = input.value;
    }
  });
  return params;
}

// ✅增强：使用配置初始化表单（完全配置驱动）
function initializeFormWithConfig() {
  if (!followupConfig) {
    console.warn("⚠️ 配置未加载，跳过表单初始化");
    return;
  }

  console.log("🔧 开始配置化表单初始化，配置内容:", followupConfig);

  // ✅新增：基于form_fields动态生成所有下拉选项
  if (followupConfig.form_fields) {
    followupConfig.form_fields.forEach(fieldConfig => {
      if (fieldConfig.input_type === 'select' && fieldConfig.options) {
        const selectElement = document.querySelector(`[name="${fieldConfig.field}"]`);
        if (selectElement) {
          console.log(`🔧 配置化字段 ${fieldConfig.field}，选项数量:`, fieldConfig.options.length);
          
          // 清空现有选项
          selectElement.innerHTML = "";
          
          // 添加默认选项
          const defaultOption = document.createElement("option");
          defaultOption.value = "";
          defaultOption.textContent = `请选择${fieldConfig.display_name || fieldConfig.field}`;
          selectElement.appendChild(defaultOption);
          
          // 动态添加选项
          fieldConfig.options.forEach((option, index) => {
            console.log(`添加选项 ${index}:`, option);
            const optionElement = document.createElement("option");
            optionElement.value = option;
            optionElement.textContent = option;
            selectElement.appendChild(optionElement);
          });
          
          console.log(`✅ 字段 ${fieldConfig.field} 选项生成完成`);
        }
      }
    });
  }

  console.log("✅ 表单配置化初始化完成");
}

// ✅页面初始化：启动配置驱动架构
async function initializePage() {
  try {
    console.log("🚀 开始初始化随访模块...");
    await loadFollowupConfig();
    
    // 绑定导出按钮事件
    bindExportButtons();
    console.log("✅ 导出按钮事件绑定完成");
    
    console.log("✅ 随访模块初始化完成");
  } catch (error) {
    console.error("❌ 随访模块初始化失败:", error);
    if (window.Swal) {
      Swal.fire("初始化失败", error.message, "error");
    }
  }
}

// ✅使用QueryResultTable组件渲染学生表格（与视力模块完全一致）
async function renderStudentTableWithComponent(students) {
  if (!window.renderQueryResultTable) {
    console.error("❌ QueryResultTable组件未加载");
    return;
  }

  // 显示结果表格容器
  document.getElementById("search-results").style.display = "block";

  try {
    // 使用新的自包含QueryResultTable API
    await window.renderQueryResultTable(students, 'followup', 'query', {
      showRowNumber: true,
      onRowClick: (row, index) => {
        // 点击学生行事件
      }
    });
    

  } catch (error) {
    console.error('❌ 随访模块表格渲染失败:', error);
    
    // 降级处理：显示错误信息
    const tableBody = document.getElementById('queryTableBody');
    if (tableBody) {
      tableBody.innerHTML = `
        <tr>
          <td colspan="100%" class="text-center text-danger py-4">
            <i class="fas fa-exclamation-triangle fa-2x mb-2 d-block"></i>
            <div>表格渲染失败: ${error.message}</div>
          </td>
        </tr>
      `;
    }
  }
}

// DOM加载完成后初始化
document.addEventListener("DOMContentLoaded", function () {
  console.log("🚀 随访模块DOM加载完成，开始初始化...");
  initializePage();
});
function applyConfigToInterface() {
  if (!followupConfig || !followupConfig.select_options) return;
  Object.keys(followupConfig.select_options).forEach((fieldName) => {
    const select = document.querySelector(`select[name="${fieldName}"]`);
    if (select) {
      // 清空现有选项，保留第一个空选项
      while (select.children.length > 1) {
        select.removeChild(select.lastChild);
      }
      // 添加配置选项
      followupConfig.select_options[fieldName].forEach((option) => {
        const opt = document.createElement("option");
        opt.value = option;
        opt.textContent = option;
        select.appendChild(opt);
      });
    }
  });
}

// 配置驱动的数据收集
function collectFormDataByConfig(formData) {
  const payload = { student_id: selectedStudent.id };

  if (followupConfig && followupConfig.form_fields) {
    // 使用配置字段收集数据
    followupConfig.form_fields.forEach(fieldConfig => {
      const fieldName = fieldConfig.field;
      if (fieldName !== 'student_id') {
        const value = formData.get(fieldName);
        // 修复：允许空字符串，这样用户可以清空字段
        if (value !== null && value !== undefined) {
          payload[fieldName] = value;
        }
      }
    });
  } else {
    // 配置加载失败时的错误处理
    console.error("❌ 随访配置未加载，无法提交表单");
    Swal.fire("配置错误", "系统配置未加载，请刷新页面重试", "error");
    return null;
  }

  console.log("收集到的表单数据:", payload);
  return payload;
}

function renderPagination(total, page, per_page) {
  const pageCount = Math.ceil(total / per_page);
  if (pageCount <= 1) {
    document.getElementById("pagination-bar").innerHTML = "";
    return;
  }
  let html = "";
  html += `<button class="page-btn" ${
    page === 1 ? "disabled" : ""
  } data-page="${page - 1}">上一页</button>`;
  let start = Math.max(1, page - 2);
  let end = Math.min(pageCount, page + 2);
  if (start > 1) html += "<span>...</span>";
  for (let i = start; i <= end; i++) {
    html += `<button class="page-btn${
      i === page ? " active" : ""
    }" data-page="${i}">${i}</button>`;
  }
  if (end < pageCount) html += "<span>...</span>";
  html += `<button class="page-btn" ${
    page === pageCount ? "disabled" : ""
  } data-page="${page + 1}">下一页</button>`;
  document.getElementById("pagination-bar").innerHTML = html;

  document.querySelectorAll(".page-btn").forEach((btn) => {
    btn.addEventListener("click", function () {
      const toPage = parseInt(this.getAttribute("data-page"));
      if (!isNaN(toPage) && toPage !== page) {
        // 重新执行查询，传递当前查询参数和页码
        const currentParams = getCurrentQueryParams();
        currentParams.page = toPage;
        onSearch(currentParams);
      }
    });
  });
}

// === 使用统一组件渲染学生信息栏 ===
async function renderStudentInfoBarByConfig(student) {
  try {
    console.log("🎯 使用统一组件渲染学生信息栏，学生信息:", student);
    
    // 使用统一的学生信息条组件
    await renderStudentInfoBar(student, {
      moduleName: 'followup',
      containerId: 'student-info-bar',
      autoShow: true,
      onError: (error) => {
        console.error("❌ 学生信息条组件渲染失败:", error);
      }
    });
    
    console.log("✅ 学生信息栏渲染完成");
    
  } catch (error) {
    console.error("❌ 学生信息栏渲染失败:", error);
  }
}

// 随访记录页面的学生查询函数（查询有随访记录的学生）
function queryStudents(page = 1) {
  const student_name = document
    .querySelector("input[name='name']")
    .value.trim();
  const educationId = document
    .querySelector("input[name='education_id']")
    .value.trim();
  const student_school = document
    .querySelector("select[name='school']")
    .value.trim();
  const student_gender = document.querySelector("select[name='gender']").value;

  // 调用统一查询接口查询学生信息
  let url = `/api/students/query?name=${encodeURIComponent(
    student_name
  )}&education_id=${encodeURIComponent(
    educationId
  )}&school=${encodeURIComponent(student_school)}&gender=${encodeURIComponent(
    student_gender
  )}&page=${page}`;
  
  const columns = getQueryColumnsForMainTable();
  if (columns.length > 0) {
    url += `&columns=${columns.join(',')}`;
  }
  
  console.log("查询有随访记录的学生，URL:", url);
  
  fetch(url)
    .then((response) => response.json())
    .then((data) => {
      console.log("随访学生查询响应:", data);
      let students = data.data || [];
      let total = data.total || 0;
      let pageNum = data.page || page;
      let perPage = data.per_page || 10;
      renderStudentTableWithComponent(students);
      renderPagination(total, pageNum, perPage);
    })
    .catch((err) => {
      console.error("随访学生查询失败:", err);
      if (window.Swal) {
        Swal.fire("查询失败", err.message, "error");
      } else {
        alert("查询失败: " + err.message);
      }
    });
}

// 修改表单提交为纯配置驱动
document
  .getElementById("followup-form")
  .addEventListener("submit", function (e) {
    e.preventDefault();
    if (!selectedStudent) {
      Swal.fire("请先选择学生", "", "info");
      return;
    }

    const formData = new FormData(this);
    const payload = collectFormDataByConfig(formData);

    if (!payload) {
      return; // 配置错误，已在函数内显示错误信息
    }

    let url, method;
    if (editingRecordId) {
      url = `/api/followup_records/${editingRecordId}`;
      method = "PUT";
    } else {
      url = "/api/followup_records";
      method = "POST";
    }

    fetch(url, {
      method: method,
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    })
      .then((res) => res.json())
      .then((data) => {
        if (data.success) {
          editingRecordId = null;
          Swal.fire("保存成功", "", "success");
          document.getElementById("followup-form").reset();
          document.getElementById("followup-form").style.display = "none";
          showHistoryTable(selectedStudent.id);
        } else {
          Swal.fire("保存失败", data.error || "未知错误", "error");
        }
      })
      .catch((err) => {
        Swal.fire("保存失败", err.message, "error");
      });
  });

// === 历史表格表头配置驱动 ===
let historyTableFields = [];
let historyTableLabels = {};

// 页面初始化时获取历史表格表头配置
initializeHistoryTableConfig();

async function initializeHistoryTableConfig() {
  try {
    const resp = await fetch("/api/config/history_fields/followup");
    const data = await resp.json();
    if (data.success) {
      historyTableFields = [];
      historyTableLabels = {};
      data.fields.forEach((item) => {
        if (item.field) {
          historyTableFields.push(item.field);
          historyTableLabels[item.field] = item.label || item.field;
        }
      });
      console.log("✅ 随访历史表格配置加载成功");
    } else {
      console.error("历史表格配置加载失败:", data.error);
    }
  } catch (e) {
    console.error("历史表格配置接口异常:", e);
  }
}

// 每次渲染历史表格后重新绑定按钮
// ======= 配置驱动历史表格渲染（使用API配置） =======
function renderConfigDrivenHistoryTable(records) {
  console.log("渲染历史表格，记录数:", records ? records.length : 0);
  console.log("历史字段配置:", historyFieldsConfig);
  
  const thead = document.querySelector("#history-table thead tr");
  const tbody = document.querySelector("#history-table tbody");
  tbody.innerHTML = "";
  
  // 检查配置是否加载
  if (!historyFieldsConfig || !Array.isArray(historyFieldsConfig)) {
    console.error("❌ 历史字段配置未加载或格式错误");
    tbody.innerHTML = `<tr><td colspan="100%" class="text-center text-danger">配置加载失败</td></tr>`;
    return;
  }
  
  // 动态渲染表头（基于配置）
  if (thead) {
    let headerHtml = "";
    historyFieldsConfig.forEach((fieldConfig) => {
      const displayName = fieldConfig.display_name || fieldConfig.field;
      headerHtml += `<th>${displayName}</th>`;
    });
    headerHtml += "<th>操作</th>";
    thead.innerHTML = headerHtml;
  }
  
  if (!records || records.length === 0) {
    tbody.innerHTML = `<tr><td colspan="${historyFieldsConfig.length + 1}" class="text-center text-muted">暂无数据</td></tr>`;
    bindArchiveButton(); // 保证无数据时也绑定
    return;
  }
  
  records.forEach((r) => {
    const row = document.createElement("tr");
    let cellsHtml = "";
    
    // 根据配置渲染数据列
    historyFieldsConfig.forEach((fieldConfig) => {
      const fieldName = fieldConfig.field;
      const value = r[fieldName] || "";
      cellsHtml += `<td>${value}</td>`;
    });
    
    // 操作列
    cellsHtml += `
        <td>
          <button class="btn btn-link btn-sm btn-show-detail" data-id="${r.id}">详情</button>
          <button class="btn btn-danger btn-sm btn-delete-record" data-id="${r.id}">删除</button>
          <button class="btn btn-secondary btn-sm btn-log-record" data-id="${r.id}">日志</button>
        </td>
      `;
    row.innerHTML = cellsHtml;
    tbody.appendChild(row);
  });
  
  // 重新绑定事件
  bindHistoryTableEvents();
  bindArchiveButton();
  
  console.log("✅ 历史表格渲染完成");
}

// 保护：所有其他现有函数保持完全不变
function showHistoryTable(studentId) {
  document.getElementById("search-results").style.display = "none";
  document.getElementById("pagination-bar").style.display = "none";
  document.getElementById("followup-form").style.display = "none";
  const area = document.getElementById("history-table-area");
  area.classList.add("show");
  area.style.display = "block";
  
  // 请求随访历史记录接口
  fetch(`/api/followup_records/list?student_id=${studentId}`)
    .then((res) => res.json())
    .then((data) => {
      if (data.success) {
        currentRecords = data.data || [];
        renderConfigDrivenHistoryTable(currentRecords);
      } else {
        console.error("获取随访历史失败:", data.error);
        currentRecords = [];
        renderConfigDrivenHistoryTable([]);
      }
    })
    .catch((error) => {
      console.error("请求随访历史异常:", error);
      currentRecords = [];
      renderConfigDrivenHistoryTable([]);
    });
}

// 重新绑定“查看全部日志”按钮（每次渲染历史表后都要绑定）
document.querySelectorAll("#btn-view-all-logs").forEach((btn) => {
  btn.onclick = function () {
    if (!selectedStudent || !selectedStudent.id) {
      Swal.fire("提示", "请先选择学生", "info");
      return;
    }
    fetch(`/api/followup_records/logs_all?student_id=${selectedStudent.id}`)
      .then((res) => res.json())
      .then((data) => {
        if (data.success && data.data.length > 0) {
          let html = data.data
            .map((log) => {
              let localTime = log.created_at
                ? new Date(log.created_at).toLocaleString()
                : "";
              return `<div style="border-bottom:1px solid #eee;margin-bottom:8px;padding-bottom:4px;">
                <div>记录ID：${log.record_id} 操作类型：${log.action} 操作人：${
                log.operator || ""
              } 时间：${localTime}</div>
                <div>原始内容：<pre style="white-space:pre-wrap;">${
                  log.old_content
                }</pre></div>
                <button class="btn btn-sm btn-outline-primary" onclick="restoreFollowupLog(${
                  log.id
                })">恢复此版本</button>
              </div>`;
            })
            .join("");
          Swal.fire({
            title: "全部操作日志",
            html: html,
            width: 900,
            showConfirmButton: false,
          });
        } else {
          Swal.fire("无日志", "该学生暂无历史日志", "info");
        }
      });
  };
});

function bindExportButtons() {
  console.log("🔗 开始绑定随访记录导出按钮事件...");
  
  // 先解绑，防止重复绑定
  document
    .querySelectorAll("#btn-export-xlsx, #btn-export-csv, #btn-export-xlsx-history, #btn-export-csv-history")
    .forEach((btn) => {
      btn.onclick = null;
    });

  // 绑定所有Excel导出按钮（包括表单区域和历史区域）
  document.querySelectorAll("#btn-export-xlsx, #btn-export-xlsx-history").forEach((btn) => {
    btn.addEventListener("click", function () {
      console.log("📊 点击Excel导出按钮:", btn.id);
      
      // 检查是否在查看具体记录详情
      if (editingRecordId) {
        console.log("📊 导出Excel（详情页面）- 记录ID:", editingRecordId);
        window.open(`/api/followup_records/${editingRecordId}/export_excel`);
      } else if (selectedStudent) {
        // 如果没有具体记录，导出该学生的所有记录
        console.log("📊 导出Excel（历史页面）- 学生信息:", selectedStudent);
        const exportUrl = `/api/followup_records/export?student_id=${selectedStudent.id}&type=xlsx`;
        console.log("📊 导出URL:", exportUrl);
        window.open(exportUrl);
      } else {
        console.log("❌ 未选择学生或记录");
        if (window.Swal) {
          Swal.fire("提示", "请先选择学生或查看具体记录", "info");
        } else {
          alert("请先选择学生或查看具体记录");
        }
        return;
      }
    });
  });

  // 绑定所有CSV导出按钮（包括表单区域和历史区域）
  document.querySelectorAll("#btn-export-csv, #btn-export-csv-history").forEach((btn) => {
    btn.addEventListener("click", function () {
      console.log("📊 点击CSV导出按钮:", btn.id);
      
      // 检查是否在查看具体记录详情
      if (editingRecordId) {
        console.log("📊 导出CSV（详情页面）- 记录ID:", editingRecordId);
        window.open(`/api/followup_records/${editingRecordId}/export_csv`);
      } else if (selectedStudent) {
        // 如果没有具体记录，导出该学生的所有记录
        console.log("📊 导出CSV（历史页面）- 学生信息:", selectedStudent);
        const exportUrl = `/api/followup_records/export?student_id=${selectedStudent.id}&type=csv`;
        console.log("📊 导出URL:", exportUrl);
        window.open(exportUrl);
      } else {
        console.log("❌ 未选择学生或记录");
        if (window.Swal) {
          Swal.fire("提示", "请先选择学生或查看具体记录", "info");
        } else {
          alert("请先选择学生或查看具体记录");
        }
        return;
      }
    });
  });
  
  console.log("✅ 随访记录导出按钮事件绑定完成");
}

document.getElementById("btn-back")?.addEventListener("click", function () {
  document.getElementById("followup-form").style.display = "none";
  document.getElementById("student-info-bar").classList.remove("show");
  document.getElementById("search-results").style.display = "block";
  document.getElementById("pagination-bar").style.display = "block";
  const area = document.getElementById("history-table-area");
  area.classList.remove("show");
  area.style.display = "none";
});

document.getElementById("btn-show-all")?.addEventListener("click", function () {
  if (!selectedStudent || !selectedStudent.id) {
    Swal.fire("请先选择学生！", "", "info");
    return;
  }
  showHistoryTable(selectedStudent.id);
});

// --- 学生档案按钮逻辑修正 ---
function updateArchiveButtonVisibility() {
  const btn = document.getElementById("btn-back-to-archive");
  if (btn) {
    btn.style.display =
      selectedStudent && selectedStudent.id ? "inline-block" : "none";
  }
  const btnHistory = document.getElementById("btn-back-to-archive-history");
  if (btnHistory) {
    btnHistory.style.display =
      selectedStudent && selectedStudent.id ? "inline-block" : "none";
  }
}

// --- 学生档案按钮逻辑最终修正 ---
function bindArchiveButton() {
  const btn = document.getElementById("btn-back-to-archive");
  if (btn) {
    btn.onclick = function () {
      const params = new URLSearchParams({
        student_id: selectedStudent.id,
        education_id: selectedStudent.education_id || "",
        name: selectedStudent.name || "",
        school: selectedStudent.school || "",
      });
      window.location.href = "/student-complete-record?" + params.toString();
    };
  }
  const btnHistory = document.getElementById("btn-back-to-archive-history");
  if (btnHistory) {
    btnHistory.onclick = function () {
      const params = new URLSearchParams({
        student_id: selectedStudent.id,
        education_id: selectedStudent.education_id || "",
        name: selectedStudent.name || "",
        school: selectedStudent.school || "",
      });
      window.location.href = "/student-complete-record?" + params.toString();
    };
  }
}

// 每次渲染表单后也绑定一次
// 只保留一次全局覆盖逻辑
if (!window._archiveBtnPatched) {
  window._archiveBtnPatched = true;
  const oldShowFollowupForm = window.showFollowupForm;
  window.showFollowupForm = function (record = null, readonly = false) {
    if (typeof oldShowFollowupForm === "function")
      oldShowFollowupForm.apply(this, arguments);
    bindArchiveButton();
  };
}

// 绑定历史表格操作按钮事件（详情/删除/日志）
function bindHistoryTableEvents() {
  console.log("绑定历史表格事件");
  
  // 详情按钮
  document.querySelectorAll(".btn-show-detail").forEach((btn) => {
    btn.onclick = function () {
      const recordId = btn.dataset.id;
      console.log("点击详情按钮，记录ID:", recordId);
      console.log("当前记录列表:", currentRecords);
      
      const record = currentRecords.find((r) => r.id == recordId);
      console.log("找到的记录:", record);
      
      if (record) {
        showFollowupForm(record, true);
      } else {
        console.error("未找到记录，ID:", recordId);
        Swal.fire("错误", "未找到对应的记录", "error");
      }
    };
  });
  
  // 删除按钮
  document.querySelectorAll(".btn-delete-record").forEach((btn) => {
    btn.onclick = function () {
      const recordId = btn.dataset.id;
      console.log("点击删除按钮，记录ID:", recordId);
      
      if (!recordId) return;
      Swal.fire({
        title: "确认删除？",
        text: "删除后无法恢复！",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "删除",
        cancelButtonText: "取消",
      }).then((result) => {
        if (result.isConfirmed) {
          fetch(`/api/followup_records/${recordId}`, { method: "DELETE" })
            .then((res) => res.json())
            .then((data) => {
              if (data.success) {
                Swal.fire("删除成功", "", "success");
                showHistoryTable(selectedStudent.id);
              } else {
                Swal.fire("删除失败", data.error || "未知错误", "error");
              }
            })
            .catch((error) => {
              console.error("删除请求失败:", error);
              Swal.fire("删除失败", error.message, "error");
            });
        }
      });
    };
  });
  
  // 日志按钮
  document.querySelectorAll(".btn-log-record").forEach((btn) => {
    btn.onclick = function () {
      const recordId = btn.dataset.id;
      console.log("点击日志按钮，记录ID:", recordId);
      
      if (!recordId) return;
      fetch(`/api/followup_records/logs?record_id=${recordId}`)
        .then((res) => res.json())
        .then((data) => {
          if (data.success && data.data.length > 0) {
            let html = data.data
              .map((log) => {
                let localTime = log.created_at
                  ? new Date(log.created_at).toLocaleString()
                  : "";
                return `<div style="border-bottom:1px solid #eee;margin-bottom:8px;padding-bottom:4px;">
                  <div>操作类型：${log.action} 操作人：${log.operator || ""} 时间：${localTime}</div>
                  <div>原始内容：<pre style="white-space:pre-wrap;">${log.old_content}</pre></div>
                  <button class="btn btn-sm btn-outline-primary mt-2" onclick="restoreFollowupLog(${log.id})">恢复此版本</button>
                </div>`;
              })
              .join("");
            Swal.fire({
              title: "操作日志",
              html: html,
              width: 900,
              showConfirmButton: false,
            });
          } else {
            Swal.fire("无日志", "该记录暂无历史日志", "info");
          }
        })
        .catch((error) => {
          console.error("获取日志失败:", error);
          Swal.fire("获取日志失败", error.message, "error");
        });
    };
  });
  
  console.log("✅ 历史表格事件绑定完成");
}

// === 显示随访录入表单 ===
async function showFollowupForm(record = null, readonly = false) {
  try {
    console.log("显示随访表单，记录:", record, "只读:", readonly);
    
    // 隐藏其他区域
    document.getElementById("search-results").style.display = "none";
    document.getElementById("pagination-bar").style.display = "none";
    document.getElementById("history-table-area").style.display = "none";
    
    // 显示表单
    const form = document.getElementById("followup-form");
    form.style.display = "block";
    
    // 使用配置驱动的表单渲染
    if (followupConfig && followupConfig.form_fields) {
      renderFollowupFormByConfig(record, readonly);
    } else {
      console.error("表单配置未加载，正在重新获取...");
      await initializeFollowupConfig();
      if (followupConfig && followupConfig.form_fields) {
        renderFollowupFormByConfig(record, readonly);
      } else {
        Swal.fire("错误", "无法加载表单配置，请刷新页面重试", "error");
        return;
      }
    }
    
    // 设置编辑状态
    if (record) {
      editingRecordId = record.id;
      document.querySelector('#followup-form .card-header').textContent = readonly ? '随访记录详情' : '编辑随访记录';
    } else {
      editingRecordId = null;
      document.querySelector('#followup-form .card-header').textContent = '电话随访录入';
    }
    
    console.log("✅ 随访表单显示成功");
    
  } catch (error) {
    console.error("显示随访表单失败:", error);
    Swal.fire("错误", "显示表单失败：" + error.message, "error");
  }
}

// 配置驱动的表单渲染函数
function renderFollowupFormByConfig(record = null, readonly = false) {
  try {
    console.log("🎯 开始渲染随访表单，配置:", followupConfig);
    
    if (!followupConfig || !followupConfig.form_fields) {
      console.error("❌ 表单配置未加载");
      return;
    }
    
    const formContainer = document.querySelector('#followup-form .card-body');
    if (!formContainer) {
      console.error("❌ 找不到表单容器");
      return;
    }
    
    // 清空现有表单内容
    formContainer.innerHTML = '';
    
    // 定义字段分组
    const fieldGroups = {
      basic: {
        title: '🕒 随访基础信息',
        className: 'section-basic-info',
        fields: ['followup_date', 'followup_time', 'followup_duration', 'followup_type', 'contact_method'],
        layout: 'compact' // 紧凑布局
      },
      personnel: {
        title: '👥 参与人员信息', 
        className: 'section-personnel',
        fields: ['interviewer', 'interviewee', 'interviewee_relation'],
        layout: 'compact'
      },
      evaluation: {
        title: '📊 干预效果评估',
        className: 'section-evaluation', 
        fields: ['intervention_satisfaction', 'intervention_effect_evaluation', 'intervention_compliance', 'vision_change_perception', 'daily_eye_use_time'],
        layout: 'normal' // 常规布局
      },
      description: {
        title: '📝 详细描述信息',
        className: 'section-description',
        fields: ['content', 'vision_improvement_details', 'vision_concern_areas', 'side_effects', 'feedback'],
        layout: 'full' // 全宽布局
      }
    };
    
    // 创建表单HTML - 使用分组布局
    let formHTML = '<form id="followup-record-form" class="followup-form-container">';
    
    // 按分组渲染字段
    Object.entries(fieldGroups).forEach(([groupKey, group]) => {
      formHTML += `<div class="form-section ${group.className}">`;
      formHTML += `<div class="form-section-title">
        <span class="icon">${group.title.substring(0, 2)}</span>
        ${group.title.substring(2)}
      </div>`;
      
      if (group.layout === 'compact') {
        // 紧凑布局 - 三列
        formHTML += '<div class="row">';
        group.fields.forEach(fieldName => {
          const fieldConfig = followupConfig.form_fields.find(f => f.field === fieldName);
          if (fieldConfig) {
            formHTML += renderFormField(fieldConfig, record, readonly, 'col-compact-3');
          }
        });
        formHTML += '</div>';
      } else if (group.layout === 'normal') {
        // 常规布局 - 两列
        formHTML += '<div class="row">';
        group.fields.forEach(fieldName => {
          const fieldConfig = followupConfig.form_fields.find(f => f.field === fieldName);
          if (fieldConfig) {
            const width = fieldName === 'daily_eye_use_time' ? 'col-md-6' : 'col-md-6';
            formHTML += renderFormField(fieldConfig, record, readonly, width);
          }
        });
        formHTML += '</div>';
      } else if (group.layout === 'full') {
        // 全宽布局 - 每个字段一行
        group.fields.forEach(fieldName => {
          const fieldConfig = followupConfig.form_fields.find(f => f.field === fieldName);
          if (fieldConfig) {
            formHTML += `<div class="textarea-group">`;
            formHTML += renderFormField(fieldConfig, record, readonly, 'col-12', true);
            formHTML += `</div>`;
          }
        });
      }
      
      formHTML += '</div>';
    });
    
    // 添加按钮区域
    formHTML += '<div class="row"><div class="col-12 text-center mt-3">';
    if (!readonly) {
      formHTML += `
        <button type="submit" class="btn btn-primary me-2">
          ${record ? '更新随访记录' : '提交随访记录'}
        </button>
        <button type="button" class="btn btn-secondary" onclick="hideFollowupForm()">取消</button>
      `;
    } else {
      formHTML += `
        <button type="button" class="btn btn-primary me-2" onclick="switchToEditMode()">编辑</button>
        <button type="button" class="btn btn-secondary" onclick="hideFollowupForm()">关闭</button>
      `;
    }
    formHTML += '</div></div>';
    
    formHTML += '</form>';
    
    // 插入表单HTML
    formContainer.innerHTML = formHTML;
    
    // 如果是新建表单，设置默认值
    if (!record) {
      setDefaultValues();
    }
    
    console.log("✅ 表单渲染完成");
    
  } catch (error) {
    console.error("❌ 表单渲染失败:", error);
    throw error;
  }
}

// 辅助函数：渲染单个表单字段
function renderFormField(fieldConfig, record, readonly, width, isTextarea = false) {
  const fieldName = fieldConfig.field;
  const label = fieldConfig.display_name || fieldConfig.label || fieldName;
  const required = fieldConfig.required || false;
  const inputType = fieldConfig.input_type || fieldConfig.type || 'text';
  const options = fieldConfig.options || [];
  
  let fieldValue = record ? (record[fieldName] || '') : '';
  
  // 统一只读状态处理
  const readonlyAttr = readonly ? 'disabled readonly' : '';
  const placeholderText = readonly ? '' : `placeholder="请输入${label}"`;
  
  let fieldHTML = '';
  
  if (isTextarea) {
    // 文本域字段 - 不需要包装div
    fieldHTML += `
      <label for="${fieldName}" class="form-label">${label}${required ? ' <span class="text-danger">*</span>' : ''}</label>
      <textarea name="${fieldName}" id="${fieldName}" class="form-control" rows="3" 
                ${readonlyAttr} ${required ? 'required' : ''}
                ${placeholderText}>${fieldValue}</textarea>
    `;
  } else {
    // 其他字段类型 - 需要包装div
    fieldHTML += `<div class="${width} form-group-compact">`;
    
    if (inputType === 'select' && options.length > 0) {
      fieldHTML += `
        <label for="${fieldName}" class="form-label">${label}${required ? ' <span class="text-danger">*</span>' : ''}</label>
        <select name="${fieldName}" id="${fieldName}" class="form-control form-select" ${readonlyAttr} ${required ? 'required' : ''}>
          <option value="">请选择${label}</option>
          ${options.map(option => 
            `<option value="${option}" ${fieldValue === option ? 'selected' : ''}>${option}</option>`
          ).join('')}
        </select>
      `;
    } else if (inputType === 'date') {
      fieldHTML += `
        <label for="${fieldName}" class="form-label">${label}${required ? ' <span class="text-danger">*</span>' : ''}</label>
        <input type="date" name="${fieldName}" id="${fieldName}" class="form-control" 
               value="${fieldValue}" ${readonlyAttr} ${required ? 'required' : ''}>
      `;
    } else if (inputType === 'time') {
      fieldHTML += `
        <label for="${fieldName}" class="form-label">${label}${required ? ' <span class="text-danger">*</span>' : ''}</label>
        <input type="time" name="${fieldName}" id="${fieldName}" class="form-control" 
               value="${fieldValue}" ${readonlyAttr} ${required ? 'required' : ''}>
      `;
    } else if (inputType === 'number') {
      fieldHTML += `
        <label for="${fieldName}" class="form-label">${label}${required ? ' <span class="text-danger">*</span>' : ''}</label>
        <input type="number" name="${fieldName}" id="${fieldName}" class="form-control" 
               value="${fieldValue}" ${readonlyAttr} ${required ? 'required' : ''}
               ${placeholderText}>
      `;
    } else {
      // 默认为文本输入
      fieldHTML += `
        <label for="${fieldName}" class="form-label">${label}${required ? ' <span class="text-danger">*</span>' : ''}</label>
        <input type="text" name="${fieldName}" id="${fieldName}" class="form-control" 
               value="${fieldValue}" ${readonlyAttr} ${required ? 'required' : ''}
               ${placeholderText}>
      `;
    }
    
    fieldHTML += '</div>';
  }
  
  return fieldHTML;
}

// 辅助函数：设置默认值
function setDefaultValues() {
  const now = new Date();
  const dateField = document.querySelector('#followup_date');
  const timeField = document.querySelector('#followup_time');
  
  if (dateField && !dateField.value) {
    dateField.value = now.toISOString().split('T')[0];
  }
  if (timeField && !timeField.value) {
    timeField.value = now.toTimeString().split(' ')[0].slice(0, 5);
  }
}

// 获取字段选项的辅助函数
function getOptionsForField(fieldName) {
  const optionsMap = {
    'followup_type': ['常规随访', '专项随访', '紧急随访', '满意度调查'],
    'interviewee_relation': ['父亲', '母亲', '祖父母', '外祖父母', '其他亲属', '本人', '其他'],
    'contact_method': ['电话', '微信', 'QQ', '短信', '当面', '其他'],
    'intervention_satisfaction': ['非常满意', '满意', '一般', '不满意'],
    'intervention_effect_evaluation': ['明显改善', '有改善', '无变化', '加重'],
    'intervention_compliance': ['完全依从', '部分依从', '不依从'],
    'vision_change_perception': ['明显好转', '略有好转', '无变化', '变差']
  };
  return optionsMap[fieldName] || [];
}

// === 显示历史记录表格 ===
function showHistoryTable(studentId) {
  console.log("显示历史记录表格，学生ID:", studentId);
  
  document.getElementById("search-results").style.display = "none";
  document.getElementById("pagination-bar").style.display = "none";
  document.getElementById("followup-form").style.display = "none";
  
  const area = document.getElementById("history-table-area");
  area.classList.add("show");
  area.style.display = "block";
  
  // 请求该学生的随访历史记录
  const url = `/api/followup_records/list?student_id=${studentId}`;
  console.log("请求历史记录URL:", url);
  
  fetch(url)
    .then((res) => res.json())
    .then((data) => {
      console.log("历史记录API响应:", data);
      if (data.success) {
        currentRecords = data.data || [];
        console.log("获取到的历史记录:", currentRecords);
        renderConfigDrivenHistoryTable(currentRecords);
      } else {
        console.error("获取随访历史失败:", data.error);
        currentRecords = [];
        renderConfigDrivenHistoryTable([]);
        Swal.fire("错误", "获取随访历史失败：" + data.error, "error");
      }
    })
    .catch((error) => {
      console.error("请求随访历史异常:", error);
      currentRecords = [];
      renderConfigDrivenHistoryTable([]);
      Swal.fire("错误", "请求随访历史异常：" + error.message, "error");
    });
}

// ==================== URL参数处理功能 ====================
// 统一的URL参数处理函数
function initializeFromParams() {
  try {
    const urlParams = new URLSearchParams(window.location.search);
    const studentId = urlParams.get("student_id");
    const autoExpand = urlParams.get("auto_expand");
    const fromComplete = urlParams.get("fromComplete") || urlParams.get("from_complete"); // 兼容两种参数名
    const showHistory = urlParams.get("show_history");

    console.log("=== 随访记录页面URL参数初始化 ===");
    console.log("URL参数:", Object.fromEntries(urlParams));

    if (studentId && autoExpand === "true") {
      console.log("✅ 开始自动加载学生信息");

      if (fromComplete === "true") {
        console.log("🔧 从学生档案页面跳转，确保配置加载完成...");
        
        // 🔧 关键修复：确保配置已加载
        const ensureConfigAndShowHistory = async () => {
          try {
            if (!historyFieldsConfig) {
              console.log("⏳ 配置未加载，等待配置加载完成...");
              await loadFollowupConfig();
              console.log("✅ 配置加载完成");
            }
            
            // 从URL参数构建学生信息
            const studentFromUrl = {
              id: parseInt(studentId),
              name: urlParams.get("name") || "",
              education_id: urlParams.get("education_id") || "",
              school: urlParams.get("school") || "",
              class_name: urlParams.get("class_name") || "",
              grade: urlParams.get("grade") || "",
              gender: urlParams.get("gender") || "",
              birthday: urlParams.get("birthday") || "",
              parent_name: urlParams.get("parent_name") || "",
              id_card: urlParams.get("id_card") || "",
              phone: urlParams.get("phone") || "",
              address: urlParams.get("address") || ""
            };

            console.log("✅ 从URL构建的学生信息:", studentFromUrl);
            selectedStudent = studentFromUrl;
            window.selectedStudent = selectedStudent;
            
            // 填充学生信息条
            fillStudentInfoBar(selectedStudent);

            // 显示学生信息条
            const studentInfoBar = document.getElementById("student-info-bar");
            if (studentInfoBar) {
              studentInfoBar.classList.add("show");
              studentInfoBar.style.display = "flex";
            }

            console.log("✅ 配置已加载，显示学生历史记录");
            showHistoryTable(studentId);
            console.log("✅ 学生信息加载完成");
            
          } catch (error) {
            console.error("❌ 配置加载或初始化失败:", error);
            if (window.Swal) {
              Swal.fire("配置加载失败", error.message, "error");
            }
          }
        };
        
        // 异步执行配置检查和历史记录显示
        ensureConfigAndShowHistory();
      } else {
        // 通过API加载学生信息
        loadStudentBaseInfo(studentId, () => {
          if (showHistory === "true") {
            showHistoryTable(studentId);
          } else {
            showFollowupForm();
          }
          console.log("✅ API学生信息加载完成");
        });
      }

      // 清除URL参数
      const newUrl = window.location.pathname;
      window.history.replaceState({}, document.title, newUrl);
    }
  } catch (error) {
    console.error("初始化参数处理失败:", error);
    if (window.Swal) {
      Swal.fire("错误", "页面初始化失败，请刷新重试", "error");
    }
  }
}

// 填充学生信息条（使用统一组件）
async function fillStudentInfoBar(student) {
  try {
    console.log("使用统一组件填充学生信息条:", student);
    
    // 使用统一的学生信息条组件
    await renderStudentInfoBar(student, {
      moduleName: 'followup',
      containerId: 'student-info-bar',
      autoShow: true,
      onError: (error) => {
        console.error("❌ 学生信息条组件渲染失败:", error);
      }
    });
    
    console.log("✅ 学生信息条填充完成");
  } catch (error) {
    console.error("填充学生信息条失败:", error);
  }
}

// 通过API加载学生基本信息
function loadStudentBaseInfo(studentId, callback) {
  console.log("加载学生基本信息，student_id:", studentId);
  
  // 统一使用student_id参数进行跨表查询
  fetch(`/api/students/get?student_id=${studentId}`)
    .then(response => response.json())
    .then(data => {
      if (data.success && data.student) {
        selectedStudent = data.student;
        window.selectedStudent = selectedStudent;
        
        console.log("✅ 学生信息加载成功:", selectedStudent.name);
        
        if (callback) callback(selectedStudent);
      } else {
        console.error("加载学生信息失败:", data.message || '未知错误');
        if (window.Swal) {
          Swal.fire("错误", data.message || "加载学生信息失败", "error");
        }
        if (callback) callback(null);
      }
    })
    .catch(error => {
      console.error("加载学生信息异常:", error);
      if (window.Swal) {
        Swal.fire("错误", "加载学生信息异常", "error");
      }
      if (callback) callback(null);
    });
}

// ==================== 页面初始化 ====================
console.log("随访记录模块脚本加载完成");

// 隐藏随访表单
function hideFollowupForm() {
  document.getElementById("followup-form").style.display = "none";
  document.getElementById("search-results").style.display = "block";
  document.getElementById("pagination-bar").style.display = "block";
  editingRecordId = null;
}

// === 编辑模式切换功能 ===
function switchToEditMode() {
  try {
    console.log("切换到编辑模式，当前记录ID:", editingRecordId);
    
    if (!editingRecordId) {
      Swal.fire("错误", "无法获取记录ID，请重新进入详情页面", "error");
      return;
    }
    
    // 获取当前记录数据
    fetch(`/api/followup_records/${editingRecordId}`)
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          const record = data.data;
          console.log("获取到记录数据:", record);
          
          // 重新渲染表单为编辑模式
          showFollowupForm(record, false); // false表示非只读模式
          
        } else {
          console.error("获取记录失败:", data.error);
          Swal.fire("错误", "获取记录数据失败：" + data.error, "error");
        }
      })
      .catch(error => {
        console.error("请求记录数据异常:", error);
        Swal.fire("错误", "请求记录数据异常：" + error.message, "error");
      });
      
  } catch (error) {
    console.error("切换编辑模式失败:", error);
    Swal.fire("错误", "切换编辑模式失败：" + error.message, "error");
  }
}

// === 日志恢复功能 ===
function restoreFollowupLog(logId) {
  try {
    console.log("恢复日志，日志ID:", logId);
    
    if (!logId) {
      Swal.fire("错误", "日志ID无效", "error");
      return;
    }
    
    // 确认恢复操作
    Swal.fire({
      title: '确认恢复',
      text: '确定要恢复到这个历史版本吗？当前数据将被覆盖！',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: '确定恢复',
      cancelButtonText: '取消'
    }).then((result) => {
      if (result.isConfirmed) {
        // 执行恢复操作
        fetch('/api/followup_records/restore', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            log_id: logId
          })
        })
        .then(response => response.json())
        .then(data => {
          if (data.success) {
            console.log("恢复成功:", data);
            
            Swal.fire({
              title: '恢复成功',
              text: '数据已恢复到历史版本',
              icon: 'success',
              confirmButtonText: '确定'
            }).then(() => {
              // 关闭日志弹窗
              Swal.close();
              
              // 刷新当前显示的数据
              if (selectedStudent && selectedStudent.id) {
                const historyArea = document.getElementById("history-table-area");
                const formArea = document.getElementById("followup-form");
                
                if (historyArea.style.display !== "none") {
                  // 如果在历史记录页面，刷新历史表格
                  showHistoryTable(selectedStudent.id);
                } else if (formArea.style.display !== "none" && editingRecordId) {
                  // 如果在详情/编辑页面，重新加载记录详情
                  fetch(`/api/followup_records/${editingRecordId}`)
                    .then(response => response.json())
                    .then(recordData => {
                      if (recordData.success) {
                        showFollowupForm(recordData.data, true); // 重新显示为只读模式
                      }
                    })
                    .catch(error => {
                      console.error("重新加载记录失败:", error);
                    });
                }
              }
            });
            
          } else {
            console.error("恢复失败:", data);
            // 优先使用message字段，其次使用error字段
            let errorMessage = data.message || data.error || "恢复操作失败，请重试";
            
            // 如果有详细信息，追加显示
            if (data.details) {
              errorMessage += "\n详细信息: " + data.details;
            }
            
            Swal.fire("恢复失败", errorMessage, "error");
          }
        })
        .catch(error => {
          console.error("恢复请求异常:", error);
          Swal.fire("恢复失败", "恢复请求异常：" + error.message, "error");
        });
      }
    });
    
  } catch (error) {
    console.error("日志恢复功能异常:", error);
    Swal.fire("错误", "日志恢复功能异常：" + error.message, "error");
  }
}

// ✅随访模块专用：操作按钮处理函数（供QueryResultTable组件调用）
function showStudentHistory(studentId) {
  console.log("显示随访历史，学生ID:", studentId);
  loadStudentBaseInfo(studentId, function(student) {
    selectedStudent = student;
    if (student) {
      renderStudentInfoBarByConfig(student);
      showHistoryTable(studentId);
    }
  });
}

function selectStudent(studentId) {
  console.log("选择学生进行随访录入，学生ID:", studentId);
  loadStudentBaseInfo(studentId, function(student) {
    selectedStudent = student;
    if (student) {
      renderStudentInfoBarByConfig(student);
      showFollowupForm(); // 显示录入表单
    }
  });
}

// ✅新增：显示学生基本信息（随访模块查询按钮）
function showStudentInfo(studentId) {
  console.log("👤 显示学生基本信息，学生ID:", studentId);
  console.log("🔍 开始调用 loadStudentBaseInfo...");
  loadStudentBaseInfo(studentId, (student) => {
    console.log("📞 loadStudentBaseInfo 回调被执行，学生数据:", student);
    if (student) {
      console.log("✅ 学生数据存在，开始填充信息栏和显示历史记录");
      // 显示学生信息并展示历史记录
      fillStudentInfoBar(student);
      
      // 显示学生信息条
      const studentInfoBar = document.getElementById("student-info-bar");
      if (studentInfoBar) {
        studentInfoBar.classList.add("show");
        studentInfoBar.style.display = "flex";
      }
      
      console.log("📊 准备调用 showHistoryTable，学生ID:", student.id);
      showHistoryTable(student.id);  // 使用学生对象的id属性
      console.log("✅ showStudentInfo 函数执行完成");
    } else {
      console.error("❌ 学生数据为空或undefined");
    }
  });
}

// ✅新增：新增随访记录（随访模块录入按钮）
function addFollowupRecord(studentId) {
  console.log("📋 新增随访记录，学生ID:", studentId);
  loadStudentBaseInfo(studentId, (student) => {
    if (student) {
      // 显示学生信息并打开录入表单
      fillStudentInfoBar(student);
      
      // 显示学生信息条
      const studentInfoBar = document.getElementById("student-info-bar");
      if (studentInfoBar) {
        studentInfoBar.classList.add("show");
        studentInfoBar.style.display = "flex";
      }
      
      showFollowupForm();
    }
  });
}

// ✅新增：全局函数声明（供HTML onclick调用）
window.showStudentInfo = showStudentInfo;
window.addFollowupRecord = addFollowupRecord;
window.showHistoryTable = showHistoryTable; // 添加showHistoryTable的全局暴露

// 🔧 修复：页面加载完成后初始化URL参数
initializeFromParams();
